import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'
import { RoomEnvironment } from 'three/examples/jsm/environments/RoomEnvironment'

let renderer, scene, camera
let controls

init()
initEnv()
loadModel()
animate()

window.onresize = function () { 
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix()
    renderer.setSize(window.innerWidth, window.innerHeight)
}

function init(params) {
    renderer = new THREE.WebGLRenderer({
        antialias: true,
    })
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.setSize(window.innerWidth, window.innerHeight)
    renderer.outputEncoding = THREE.sRGBEncoding
    document.body.appendChild(renderer.domElement)

    //camera
    camera = new THREE.PerspectiveCamera(45, window.innerWidth, window.innerHeight, 1, 100)
    camera.position.set(5, 2, 8)
    

    //scene
    scene = new THREE.Scene()
    scene.background =  new THREE.Color(0x888888)
    scene.add(new THREE.AxesHelper(1))

    //controls
    controls = new OrbitControls(camera, renderer.domElement)
    controls.target.set(0, 0.5, 0)
    controls.update()
    controls.enablePan = false
    controls.enableDamping = true
}

function initEnv(params) {
    var pmeremGenerator = new THREE.PMREMGenerator(renderer)
    scene.environment = pmeremGenerator.fromScene(new RoomEnvironment(),0.001).texture
}

function loadModel(params) {
    const loader = new GLTFLoader()
    const dracoLoader = new DRACOLoader()
    dracoLoader.setDecoderPath('./draco/gltf/')
    loader.setDRACOLoader(dracoLoader)
    loader.load(
        'models/gltf/LittlestTokyo.glb',function (gltf) {
            console.log(gltf);
            const model = gltf.scene
            scene.add(model)
            gltf.scene.traverse(function (child) {
                if (child.isMesh) {
                    console.log(child);
                }
            });
            console.log(model.position);
            model.position.set(1, 1, 0)
            model.scale.set(0.01,0.01,0.01)
        }
    )
}

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene,camera)
}
